//
//  MJRefreshExample.swift
//  SwiftCode
//
//  Created by yuhus on 2023/5/4.
//

import Foundation
import UIKit
import MJRefresh

class MJRefreshExample: UIViewController {
  override func viewDidLoad() {
    super.viewDidLoad()
    view.backgroundColor = .white
    
    view.addSubview(tableView)
    tableView.snp.makeConstraints { make in
      make.edges.equalTo(view.safeAreaLayoutGuide)
    }
    
    initData()
  }
  
  private func initData() {
    tableView.mj_header = MJRefreshNormalHeader(refreshingBlock: { [weak self] in
      self?.delay(seconds: 1) {
        self?.tableView.mj_header?.endRefreshing()
      }
    })
    
    tableView.mj_footer = MJRefreshBackNormalFooter(refreshingBlock: { [weak self] in
      self?.delay(seconds: 1, closure: {
        self?.tableView.mj_footer?.endRefreshing {
          print("mj_footer endRefreshing")
        }
      })
    })
    
    //    scrollView.bounces = false
    tableView.contentOffset.y = 1
  }
  
  private func delay(seconds: Int, closure: @escaping ()->()) {
    let time = DispatchTime.now() + .seconds(seconds)
    DispatchQueue.main.asyncAfter(deadline: time) {
      print("🕑")
      closure()
    }
  }
  
  private lazy var tableView: UITableView = {
    let tableView = UITableView(frame: .zero, style: .plain)
    tableView.backgroundColor = .clear
    tableView.dataSource = self
//    (tableView as UIScrollView).delegate = self
    tableView.register(UITableViewCell.self, forCellReuseIdentifier: String(describing: UITableViewCell.self))
    return tableView
  }()
  
  let tableCount = 20
}

extension MJRefreshExample: UITableViewDataSource {
  func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return tableCount
  }
  
  func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: String(describing: UITableViewCell.self), for: indexPath)
    cell.textLabel?.text = "row: \(indexPath.row)"
    cell.textLabel?.textColor = .black
    cell.backgroundColor = .clear
    return cell
  }
}
